package io.jee.caisan.weixin.config.web.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import io.jee.caisan.weixin.config.SessionManager;
import io.jee.caisan.weixin.config.UrlManager;
import io.jee.caisan.weixin.domain.Member;
import io.jee.caisan.weixin.service.MemberService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;

public class WxmpUserInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private MemberService memberService;
	
	@Resource
	private SessionManager sessionManager;
	
	@Resource
	private WxMpService wxService;
	
	@Resource
	private UrlManager urlManager;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String openid = sessionManager.getSessionOpenid(request);
		Member member = sessionManager.getSessionMember(request);
		if(ObjectUtils.isEmpty(member)) {
			member = memberService.findByOpenid(openid);
			sessionManager.setSessionMember(request, member);
		}
		if(ObjectUtils.isEmpty(member)) {
			String oauth2Url = wxService.oauth2buildAuthorizationUrl(urlManager.login(), WxConsts.OAuth2Scope.SNSAPI_BASE, "LOGIN");
			this.logger.info("not member is redirect : " + oauth2Url);
			response.sendRedirect(oauth2Url);
			return false;
		}
		return true;
	}
}